/**
* @description: 路由器业务信息完善
* @author: JiWei
* @remark:
**/
<template>
  <view class="add-patrol-main">
    <nav-bar class="header" back title="路由器业务信息完善" @goBack="goBack"/>
    <div class="main-container">
      <!-- 业务信息 -->
      <div class="fibre-info">
        <view class="plan-info-title">
          <plateTitle title="路由器业务" :isRequired="false" class="plate-title">
            <slot>
              <img class="palant-img" src="../../../../static/img/ywadd.png" alt="" @click="addType">
            </slot>
          </plateTitle>
        </view>
        <van-form ref="formRule">
          <view class="router-business" v-for="(item,index) in chooseList" :key="index">
            <view class="business-img">
              <img @click="removeType(item,index)" src="../../../../static/img/delete.png" alt="">
            </view>

            <van-field input-align="right" disabled v-model="item.routerBuzName" class="cur_dis_input"  label="业务名称"
                       :rules="item.routerBuzNameRule" placeholder="请选择" right-icon="arrow"
                       required @click-right-icon="handleSelecBuinessName(index)" />
            <van-field input-align="right" disabled v-model="item.portType" class="cur_dis_input" label="端口类型"
                       :rules="item.portTypeRule" placeholder="请选择" right-icon="arrow"
                       required @click-right-icon="handleSelecBuiness(index)" />
            <van-row>
              <van-col span="6">
                <van-field label="端口" required />
              </van-col>
              <van-col span="6">
                <van-field v-model="item.slotc" placeholder="槽" type="number" :rules="item.slotcRule" />
              </van-col>
              <van-col span="6">
                <van-field v-model="item.subslot" placeholder="子槽" type="number" :rules="item.subSlotRule" />
              </van-col>
              <van-col span="6">
                <van-field v-model="item.portName" placeholder="端口" type="number" :rules="item.prorNameRule" />
              </van-col>
            </van-row>
          </view>
        </van-form>
        <view class="plan-info-title">
          <plateTitle title="巡视信息" :isRequired="false" class="plate-title"></plateTitle>
        </view>
        <!-- 设备照片 -->
        <view class="patrol-info-container">
          <view>设备照片</view>
          <van-divider dashed />
          <div class="image-wrap">
            <div class="image-list">
              <div
                  class="upload-button"
                  v-for="(imgItem, index) in files"
                  :style="{'background-image': `url(${imgItem.bgImg})`}"
                  @click.stop="imageHandle(imgItem, index, 'CHOOSE')"
              >
                <div v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgItem, index, 'DELETE')">×</div>
                <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, index, 'PREVIEW')">
              </div>
            </div>
          </div>
        </view>
        <!-- 备注 -->
        <view class="remark-info-container">
          <view>备注</view>
          <van-divider dashed />
          <div class="remark-wrap">
            <textarea class="remark-text" v-model="currentData.otherProps.remark">
          </textarea>
          </div>
        </view>
        <!-- 巡视结果 -->
        <view class="result-info-container">
          <van-cell-group v-for="(item, index) in currentData.tourInfoProps" :key="index">
            <!-- 不可编辑框 -->
            <van-field
                v-if="item.elementType === 'TEXT'"
                :required="item.isRequired"
                readonly
                input-align="right"
                :value="item.value"
                :label="item.title"
            />
          </van-cell-group>
        </view>
      </div>
    </div>
    <!--按钮-->
    <van-button block @click="saveOptical" >提交</van-button>
    <!--时间选择器-->
<!--    <van-popup v-model="showTimePicker" position="bottom">-->
<!--      <van-datetime-picker-->
<!--          v-model="currentDate"-->
<!--          type="year-month"-->
<!--          title="选择年月"-->
<!--          :formatter="formatter"-->
<!--          :min-date="minDate"-->
<!--          show-toolbar-->
<!--          cancel-button-text="清空"-->
<!--          @confirm="pickerConfirm"-->
<!--          @cancel="pickerEmpty"-->
<!--      />-->
<!--    </van-popup>-->
    <van-popup v-model="showNamePicker" position="bottom">
      <van-picker ref="typePicker" show-toolbar :columns="typeColumns" cancel-button-text="清空"
                  @confirm="onTypeConfirm" @cancel="pickerNameEmpty" />
    </van-popup>
    <van-popup v-model="showTorpPicker" position="bottom">
      <van-picker ref="typePicker" show-toolbar :columns="stateColumns" cancel-button-text="清空"
                  @confirm="onStateConfirm" @cancel="pickerTorpEmpty" />
    </van-popup>
    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <div style="width: 100%; text-align: center;">{{ image.previewName }}</div>
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </view>
</template>
<script>
import wx from "../../../../static/common_js/jweixin_1.0.0";

let infoOptical_add = {
  otherProps: {
    "remark": "",        //备注
  },
  tourInfoProps: { // 显示的属性。包含巡视人和巡视时间
    "tourOperName": {
      title: "巡视人",
      keys: "tourOperName",
      value: "",
      isRequired: false,
      elementType: "TEXT"
    }, //设备名称
    "tourTimStr": {
      title: "巡视时间",
      keys: "tourTimStr",
      value: "",
      isRequired: false,
      elementType: "TEXT"
    },   //所属站点名称
  },
  hideProps:{
    "taskId":"task001",    //所属工单id    //必填
    "siteid": "s001",   //所属站点
    "sitename": "",   //所属站点
    "tourOperId": "2",      //巡检人ID  必填      userId放进来
    "tourOperName": "2",    //巡检人名称    必填       userName放进来
    "producerIdCustom": "", // 自定义设备厂家名称
    "modelnumberCustom": "" // 自定义设备型号名称
  },
}
let fileTemplate = [
  {
    name: "EQUIPMENT.jpg",
    previewName: "正面照片",
    type: "EQUIPMENT",
    bgImg: require("../../../../static/img/lyqzm.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "NAMEPLATE.jpg",
    previewName: "反面照片",
    type: "NAMEPLATE",
    bgImg: require("../../../../static/img/lyqfm.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "OTHER.jpg",
    previewName: "其他照片",
    type: "OTHER",
    bgImg: require("../../../../static/img/bg_qita.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
import navBar from "../../../../components/common/nav-bar";
import plateTitle from '../../../../components/business/plateTitle.vue';
import { Dialog, Toast } from 'vant'
import moment from "moment/moment";
import axios from "axios";
import {mapGetters} from "vuex";
import config from "../../../../common/config";

export default {
  name: 'routerBusinessInformationPerfection',
  components: { navBar,plateTitle },
  props: {},
  data() {
    return {
      baseUrl: '',
      currentData: {}, // 当前基本信息
      showTimePicker: false,
      currentDate: "",
      minDate: new Date(0),
      showPicker: false,
      currentChangeItem: '', // 当前正在修改的下拉项
      chooseList:[],
      files: {}, // 照片map
      showPreview: false,
      showNamePicker:false,
      showTorpPicker:false,
      typeColumns:[],
      stateColumns:[],
      keyIndex:'',
      typeIndex:'',
      type:'',
      objId:'',
      taskId:'',
      state:'',
      taskSiteId:'',
      taskSiteName:'',
    };
  },
  computed: {
    ...mapGetters(['userData'])
  },
  watch: {},
  onLoad(option) {
      config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
    })
    this.type = option.type
    this.objId = option.objId
    this.taskId = option.taskId
    this.state = option.state
    this.taskSiteId = option.taskSiteId
    this.taskSiteName = option.taskSiteName
    this.currentData = JSON.parse(JSON.stringify(infoOptical_add));
    this.files = JSON.parse(JSON.stringify(fileTemplate));
    this.currentData.hideProps = {
      // 新增业务线  taskid还未带过来，所属站点暂时不能选，
      parStationId: option.taskSiteId,   //所属站点
      taskId: option.taskId, //所属工单id    //必填
      siteid: option.taskSiteId, //所属站点
      sitename: option.taskSiteName, //所属站点name
      tourOperId: this.userData.userId, //巡检人ID  必填      userId放进来
      tourOperName: this.userData.userName, //巡检人名称    必填       userName放进来
      producerIdCustom:'',
      modelnumberCustom:'',
    }
    this.getBusinessInfo()
  },
  methods: {
    goBack() {
      if(this.type === 'reEdit') {
        uni.navigateTo({
          url:`/pages/workBench/todoTask/routerPatrol/RouterTourDetails?objId=${this.objId}&taskSiteId=${this.taskSiteId}&state=${this.state}
          &taskId=${this.taskId}&taskSiteName=${this.taskSiteName}`
        })
      }else {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/routerPatrol/routerOperationalVerification?objId=${this.objId}&taskSiteId=${this.taskSiteId}&state=${this.state}&taskId=${this.taskId}&taskSiteName=${this.taskSiteName}`,
        })
      }
    },
     // 清空业务名称已选
    pickerNameEmpty(){
      this.showNamePicker = false
      this.chooseList[this.keyIndex].routerBuzName = ''
    },
    // 清空端口类型已选
    pickerTorpEmpty(){
      this.showTorpPicker = false
      this.chooseList[this.typeIndex].portType = ''
    },
    addType() {
      this.chooseList.push({
        routerBuzName:'',
        portType:'',
        slotc:'',
        subslot:'',
        portName:'',
        routerBuzNameRule:[{
          required: true,
          trigger: 'onSubmit'
        }],
        portTypeRule:[{
          required: true,
          trigger: 'onSubmit'
        }],
        slotcRule:[{
          required: true,
          trigger: 'onSubmit'
        }],
        subSlotRule:[{
          required: true,
          trigger: 'onSubmit'
        }],
        prorNameRule:[{
          required: true,
          trigger: 'onSubmit'
        }],
      })
    },
    removeType(item,index) {
      this.chooseList.splice(index,1)
    },
    getBusinessInfo(){
      this.$api.queryRouterBuz({ routerid: this.objId }).then(res => {
        console.log('业务数据', res.data)
        this.chooseList = res.data.ROUBUZ
        this.total = res.data.TOTAL_NUMBER
        this.currentData.otherProps.remark = res.data.ROUBREM[0].remark
        this.currentData.tourInfoProps['tourOperName'].value = res.data.ROUBREM[0].tourOperName
        this.currentData.tourInfoProps['tourTimStr'].value = moment(res.data.ROUBREM[0].tourTim).format('YYYY-MM-DD HH:mm')
        if(res.data.files.length === 0) {
          this.files = JSON.parse(JSON.stringify(fileTemplate));
        }else {
          this.files = this.files.map((item) => {
            return {
              ...item,
              img: res.data.files[item.type] ? this.baseUrl + res.data.files[item.type]: '',
            }
          })
        }
      })
    },
    imageHandle (imgItem, imgIndex, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除${imgItem.previewName}`
        })
            .then(() => {
              this.$set(this.files, imgIndex, {
                ...this.files[imgIndex],
                raw: null,
                img: ''
              })
              this.delList.includes(imgItem.type) ? null: this.delList.push(imgItem.type);
              console.log(this.delList, "delete")

            })
            .catch(() => {
              // on cancel
            })
      }
    },
    choosePhoto(imgItem, index) {
      wx.chooseImage({
        count:3,
        sourceType: ['album','camera'],
        success: (chooseImageRes) => {
          this.h5_url_to_blob(chooseImageRes.localIds[0]).then(res => {
            this.$set(this.files, index, {
              ...this.files[index],
              raw: res,
              img: chooseImageRes.localIds[0]
            })

            if (this.delList.includes(imgItem.type)) {
              this.delList = this.delList.filter(item => {
                if (item === imgItem.type) {
                  return false;
                }

                return true;
              })
            }

          })
        }
      });
    },
    h5_url_to_blob(url) {
      return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function(e) {
          if (this.status == 200) {
            var Blob = this.response;
            // console.log(myBlob)
            resolve(Blob)
            // myBlob现在是对象URL指向的blob。
          }
        };
        xhr.send();
      })
    },
    saveOptical() {
      Toast.loading({
        duration:0,
        message: '加载中...',
        forbidClick: true,
      });
      let params = {
        objId: this.objId,
        chooseList: this.chooseList,
        ...this.currentData.hideProps,
        ...this.currentData.otherProps,
      }
      let requestParams = {
        params: JSON.stringify(params),
        files: this.files
      }
      let param = new FormData() // 创建form对象
      this.files.forEach((file) => {
        if (file.raw) {
          param.append('files', file.raw, file.name)
        }
      });
      // param.append('files', this.filesRaw[0], '测试')  // 通过append向form对象添加数据
      param.append('params', requestParams.params) // 添加form表单中其他数据
      // 添加请求头
      let config = {
        headers: { 'Content-Type': 'multipart/form-data',Authorization: uni.getStorageSync('token') || '' }
      }
      let url = "";
      // #ifndef IGW
      url = "/ap/txksh/kosinManage/rest/api/router/updateRouterBuz";
      // #endif
      // #ifdef IGW
      url = `${this.baseUrl}/txksh/kosinManage/rest/api/router/updateRouterBuz`
      // #endif
      axios
          .post(
              url,
              param,
              config
          )
          .then(response => {
            Toast.clear();

            if(response.data.code === 0) {
              // 如果当前为巡视，且返回data为0，表示重复巡视
              Dialog.confirm({
                title: "保存成功",
                showCancelButton: false,
              }).then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/routerPatrol/routerPatrol?objId=${this.objId}&taskId=${this.taskId}&state=${this.state}&taskSiteId=${this.taskSiteId}&taskSiteName=${this.taskSiteName}`
                });
              });
            } else {
              Dialog.alert({
                message: response.data.msg,
                theme: 'round-button',
              });
            }

          })
    },
    handleSelecBuinessName(index) {
      this.keyIndex = index
      let params = {
        kdCode:'BUSINESS_NAME'
      }
      this.$api.routerSelectList(params).then(res => {
        console.log(res,321)
        if (res.code == 0) {
          this.showNamePicker = true
          this.$nextTick(() => {
            this.typeColumns = res.data.list.map((item, index) => {
              return {
                text: item.NAME,
                value: item.BRIEFNAME,
              };
            });
          })
        }
        this.typeColumns = res.data.list.map(item => {
          return item.NAME
        })
      })
    },
    onTypeConfirm(value,index) {
      this.chooseList.map((item, key) => {
        if (key == this.keyIndex) {
          item.routerBuzName = value.text
        }
        return item;

      })
      this.showNamePicker = false;
    },
    onStateConfirm(value,index) {
      this.chooseList.map((item, key) => {
        if (key == this.typeIndex) {
          item.portType = value.text
        }
        return item;

      })
      this.showTorpPicker = false;
    },
    handleSelecBuiness(index) {
      this.typeIndex = index
      let params = {
        kdCode:'PORT_TYPE'
      }
      this.$api.routerSelectList(params).then(res => {
        if (res.code == 0) {
          this.showTorpPicker = true
          this.$nextTick(() => {
            this.stateColumns = res.data.list.map((item, index) => {
              return {
                text: item.NAME,
                value: item.BRIEFNAME,
              };
            });
          })
        }
        this.stateColumns = res.data.list.map(item => {
          return item.NAME
        })
      })
    },
  }
};
</script>
<style scoped lang="scss">
.add-patrol-main {
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  width: 100vw;
  min-height: 100vh;
  background-color: rgba(242,246,250,1);
  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }

  .cable-state{
    width: 100vw;
    height: px2vh(140);
    background-color: #ffffff;
    box-sizing: border-box;
    padding: 0 px2vw(30) 0 px2vw(49);
    display: flex;
    justify-content: space-between;
    align-items: center;
    .cable-state-title {
      font-size: px2vw(42);
    }
    .cable-state-text {
      width: px2vw(220);
      height: px2vh(80);
      border-radius: px2vw(40);
      font-size: px2vw(42);
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: bold;
      &.cable-state-on {
        color: rgba(255,67,85,1);
        background-color: rgba(255,67,85,0.1);
      }

      &.cable-state-off {
        color: rgba(65,220,131,1);
        background-color: rgba(65,220,131,0.1);
      }
    }
  }

  .main-container {
    padding-top: px2vh(20);
    height: calc(100vh - #{px2vh(384)});
    width: calc(100vw - #{px2vw(60)});
    margin-left: px2vw(30);
    overflow: auto;
    .fibre-info {
      .plan-info-title {
        width: calc(100% - #{px2vw(60)});
        margin-left: px2vw(30);
        margin-bottom: px2vh(30);
        .palant-img {
          width: px2vw(60);
        }
      }
      .router-business {
        width: calc(100% - #{px2vw(60)});
        height: auto;
        margin-left: px2vw(30);
        background: #fff;
        border-radius: px2vw(20);
        margin-bottom: px2vh(30);
        .business-img {
          width: 100%;
          text-align: right;
          img {
            width: px2vw(60);
          }
        }
      }
      .patrol-info-container {
        padding: px2vh(70) px2vw(50);
        font-size: px2vw(42);
        color: #666666;
        border-radius: $border-radius-base;
        overflow: hidden;
        background-color: #FFFFFF;

        /deep/ .van-radio {
          margin-right: px2vw(139.5)
        }

        .image-wrap {
          width: 100%;
          display: flex;

          img {
            width: px2vw(215);
            height: px2vw(215);
            margin-right: px2vw(40);
            border-radius: px2vw(6);
          }

          .image-list {
            width: 100%;
            display: flex;
            .upload-button {
              width: px2vw(215);
              height: px2vw(215);
              background-size: cover;
              margin-right: px2vw(40);
              position: relative;
              .delete-icon {
                position: absolute;
                top: px2vw(-20);
                right: px2vw(-20);
                width: px2vw(40);
                height: px2vw(40);
                background-color: rgba(0, 0, 0, 0.7);
                border-radius: 50%;
                color: #fff;
                display: flex;
                justify-content: center;
                align-items: center;
              }
            }
          }
        }
      }
      .remark-info-container {
        padding: px2vh(70) px2vw(50);
        font-size: px2vw(42);
        color: #666666;
        border-radius: $border-radius-base;
        overflow: hidden;
        background-color: #FFFFFF;
        margin-top: px2vh(40);
        margin-bottom: px2vh(40);

        .remark-wrap {
          background-color: #FAFAFA;
          padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
          border-radius: px2vw(20);

          .remark-text {
            height: px2vh(150);
          }
        }
      }
      .result-info-container {
        border-radius: $border-radius-base;
        overflow: hidden;
        background-color: #FFFFFF;
        .yellow {
          /deep/.van-cell__value {
            color: #FFAD0E;
          }
        }
        .blue {
          /deep/.van-cell__value {
            color: #417ADC;
          }
        }
        .green {
          /deep/.van-cell__value {
            color: #41DC83;
          }
        }
        .red {
          /deep/ .van-cell__value {
            color: #FF4355;
          }
        }
      }
    }
  }
  /deep/ .van-field__label {
    width: 9em;
  }
  /deep/.van-button {
    width: calc(100% - #{px2vw(60)});
    margin: px2vh(50) auto px2vh(71);
    height: px2vh(120);
    color: #fff;
    background-color: #417ADC;
    border: 1px solid #417ADC;
    border-radius: px2vh(60);
  }
}
.cur_dis_input {
  /deep/ .van-field__control:disabled {
    color: #333;
    -webkit-text-fill-color: currentColor;
  }
}
</style>
